var app = getApp();
var timer;
var token = wx.getStorageSync('token_key');
Page({

	/**
	 * 页面的初始数据
	 */
  data: {
    //banner轮播图
    list_banner: '',
    //头部导航
    header: ['全部', '普通抽奖团', '会员抽奖团',],
    header_select: 0,
    //监听滚动的高度
    // scrollTop:0,
    none_box: false,
    // 抽奖团列表
    group_content: [],
    //保存时间戳
    time_all: [],
    imgurl: app.urlimg,
    // 底部导航
    bottom_btns: [
      { img: '/pages/icon/group/1.png', text: '骆驼拼团' },
      { img: '/pages/icon/group/2.png', text: '抽奖团' },
      // { img: '/pages/icon/group/3.png', text: '免单团' },
    ],
    group_type: 0,
    //下拉限制（加载更多）
    go_look: true,
  },
  // 进入商品详情页面(去开团)
  click: function (e) {
    wx.navigateTo({
      url: '../../../pages/group/groupdetail/index?id=' + e.currentTarget.dataset.index + '&regiment_id=' + e.currentTarget.dataset.regiment_id + "&group_type=" + e.currentTarget.dataset.group,
      success: function () {
        clearInterval(timer);
      }
    })
  },
  //头部导航   头部为‘时间日期’
  top_click: function (e) {
    clearInterval(timer);
    var that = this;
    var header_nav = e.currentTarget.dataset.index;
    that.setData({
      header_select: e.currentTarget.dataset.index,
      defaultpages: 2,
      scrollTop: 0,
    })
    console.log(header_nav);
    //console.log(defaultpages);
    // 0为全部团  2为普通抽奖团   3为会员普通团
    if (header_nav == 1) {
      var group_type = 2
    } else if (header_nav == 2) {
      var group_type = 3
    } else {
      var group_type = 0
    }
    //数据加载
    wx.request({
      url: app.url + 'api_group/lotteryGroup',
      method: 'GET',
      data: { group_type: group_type },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      },
      success: function (res) {
        that.setData({
          group_content: res.data.result,
          group_type: group_type,
        })

        for (var i = 0; i < res.data.result.length; i++) {
          //获得后台转过来的毫秒数 储存在time_box中
          that.data.time_all.push(res.data.result[i].remain_time)
          // 获得毫秒数  转化  成小时、分钟、秒
          that.time_cipher(res.data.result[i].remain_time, i);
        }
        timer = setInterval(function () {
          var group_content = that.data.group_content;
          var time_all = that.data.time_all;
          for (var i = 0; i < group_content.length; i++) {
            that.time_cipher(time_all[i], i)
          }
        }, 1000);
      },
      //接口调用失败返回的函数
      fail: function (err) {
        console.log(err)
      }
    })
  },
  // 头部为‘时间日期’  的头部导航点击
  top_click_two: function (e) {
    var that = this;
    that.setData({
      select_index: e.currentTarget.dataset.index,
      select_index_num: e.currentTarget.dataset.num,
      scrollTop: 0,
      defaultpages: 2,
    })
    console.log(e);
    console.log('发送请求');
    that.load_fun(that, e.currentTarget.dataset.num, e.currentTarget.dataset.index);
  },
  // banner点击
  photolink: function (e) {
    var that = this
    var url = e.currentTarget.dataset.url
    if (url !== '') {
      wx.redirectTo({ url: url })
    }
  },
  //监听滚动高度
  go_scroll: function (e) {
    var that = this;
    var none_box = false;
    if (e.detail.scrollTop > 140) {
      none_box = true;
    }
    that.setData({
      none_box: none_box,
    })
  },
  // 底部导航
  buttom_navigation_click: function (e) {
    var index = e.currentTarget.dataset.index;
    var url = "";
    if (index == 0) {
      url = "/pages/group/group";
    } else if (index == 1) {
      url = "/pages/group/lottery/lottery";
    } else if (index == 2) {
      url = "/pages/group/charge/index";
    }
    wx.redirectTo({
      url: url,
    })

  },
	/**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function (options) {
    var that = this;
    // header_select
    if (!options.select) {
      var group_type = 0
    } else {
      var group_type = 3
    }
    console.log(options);
    console.log(group_type);
    that.setData({
      defaultpages: "2",   //显示页码
      header_select: (options.select != undefined ? options.select :''),
      group_type: group_type
    })

    //获取当前时间（用于页头的日期）
    var time_all = new Date();//获取当前时间
    that.setData({
      current_time: CurentTime(time_all),
    })
    app.getUserInfo(function (token_key) {
      // 头部为‘时间日期’
      that.load_fun(that, that.data.current_time);

      wx.request({
        url: app.url + 'api_group/get_banner',
        data: {
          type: 3, // 1 限时抢购 2 拼团 3 抽奖团
        },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key')
        }, success: function (res) {
          that.setData({
            list_banner: res.data.result,
          })
        }
      })
    })

    // 头部为‘全部’、‘普通抽奖团’、‘会员抽奖团’
    // wx.request({
    //   url: app.url + 'api_group/lotteryGroup',
    //   data: { group_type: group_type },
    //   header: {
    //     'content-type': 'application/json',
    //     'token': wx.getStorageSync('token_key')
    //   }, success: function (res) {
    //     console.log(res.data.result);

    //     //时间头部**********************************************************************
    //     //获取当前时间（用于页头的日期）
    //     var time_all = new Date();
    //     console.log(time_all);
    //     //获取三天前的时间
    //     time_all.setTime(time_all.getTime() - (24 * 60 * 60 * 1000) * 4);
    //     //计算天数函数
    //     function time_method() {
    //       time_all.setTime(time_all.getTime() + (24 * 60 * 60 * 1000) * 1);
    //       // console.log((time_all.getMonth() + 1) + "/" + time_all.getDate());
    //       return (time_all.getMonth() + 1) + "/" + time_all.getDate();
    //     }
    //     var day_num_all = [];
    //     for (var i = 0; i < 7; i++) {
    //       // day_num_all.push(time_method())
    //       day_num_all[i] = {};
    //       var time_method_time = time_method();
    //       day_num_all[i].date_nj = time_method_time;
    //       console.log(day_num_all[i]);
    //       var timestamp1 = Date.parse(new Date(time_method_time));
    //       timestamp1 = timestamp1 / 1000;
    //       var timestamp2 = (new Date().getMonth() + 1) + '/' + new Date().getDate();
    //       timestamp2 = Date.parse(new Date(timestamp2)) / 1000;
    //       if (timestamp1 <= timestamp2) {
    //         day_num_all[i].state = '已开始';
    //       } else if (timestamp1 > timestamp2) {
    //         day_num_all[i].state = '即将开团';
    //       } else {
    //         day_num_all[i].state = '开团中';
    //       }
    //     }
    //     console.log(day_num_all);

    //     that.setData({
    //       group_content: res.data.result,
    //       select_index: 0,
    //       day_num: day_num_all,
    //     })
    //     for (var i = 0; i < res.data.result.length; i++) {
    //       //获得后台转过来的毫秒数 储存在time_box中
    //       that.data.time_all.push(res.data.result[i].remain_time)
    //       // 获得毫秒数  转化  成小时、分钟、秒
    //       that.time_cipher(res.data.result[i].remain_time, i);
    //     }
    //   }
    // })

  },
  //加载函数
  load_fun: function (that, time_day, select_top_index) {

    wx.request({
      // url: app.url + 'api_group/lotteryGroup',
      url: app.url + 'api_team/timeBanner',
      data: {
        day: time_day,
        type: 2
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      }, success: function (res) {
        console.log(res.data.result);

        //时间头部**********************************************************************
        var banner_time = res.data.result.banner;
        var isCurrent_index = 0;
        if (banner_time != '' && banner_time != undefined) {

          var ccc = '';
          for (var i = 0; i < banner_time.length; i++) {
            var aaa = "" + banner_time[i].time;
            banner_time[i].text_day = aaa.substring(4, 6) + '/' + aaa.substring(6, 8);

            if (banner_time[i].isCurrent == 1) {
              isCurrent_index = i;
            }
          }

        }

        console.log(time_day);
        that.setData({
          group_content: res.data.result.list,
          select_index_num: res.data.result.list != '' ? time_day : (banner_time != '' ?banner_time[0].time : '0'),
        })

        if (res.data.result.list == '') {
          wx.request({
            url: app.url + 'api_team/timeBanner',
            data: {
              day: (banner_time != '' ? banner_time[0].time : '0'),
              type: 2,
            },
            header: {
              'content-type': 'application/json',
              'token': wx.getStorageSync('token_key')
            },
            success: function (res) {
              that.setData({
                group_content: res.data.result.list,
                select_index: 0,
              })
              list_time(res.data.result.list);
            },
          })

        }



        list_time(res.data.result.list);
        function list_time(list) {
          if (list != '') {
            header(banner_time);
            for (var i = 0; i < list.length; i++) {
              //获得后台转过来的毫秒数 储存在time_box中
              that.data.time_all.push(list[i].timeout)
              // 获得毫秒数  转化  成小时、分钟、秒

              if (list[i].timeout) {
                that.time_cipher(list[i].timeout, i);
              } else {
                that.time_cipher(list[i].distanceStart, i);
              }
            }
          }
        }
      }
    })

    function header(banner_time) {
      for (var g = 0; g < banner_time.length; g++) {
        if (that.data.current_time > banner_time[g].time) {
          banner_time[g].state = '已开始';
        } else if (that.data.current_time < banner_time[g].time) {
          banner_time[g].state = '即将开团';
        } else if (that.data.current_time == banner_time[g].time) {
          banner_time[g].state = '开团中';
          if (select_top_index == undefined) {
            that.setData({
              select_index: g,
            })
          }
        }
      }
      that.setData({
        day_num: banner_time,
      })

    }
  },

  // 获得毫秒数  转化  成小时、分钟、秒
  time_cipher: function (Times, index) {
    var that = this;

    Times -= 1;//减去一秒

    var day = Math.floor(Times / (60 * 60 * 24));//计算剩余的天数
    if (('' + day).length == 1) {
      day = '0' + day;
    }
    var hours = parseInt(Times / 60 / 60 % 24, 10); //计算剩余的小时
    if (('' + hours).length == 1) {
      hours = '0' + hours;
    }
    var minutes = parseInt(Times / 60 % 60, 10);//计算剩余的分钟
    if (('' + minutes).length == 1) {
      minutes = '0' + minutes;
    }
    var seconds = parseInt(Times % 60, 10);//计算剩余的秒数
    if (('' + seconds).length == 1) {
      seconds = '0' + seconds;
    }
    //倒计时判断
    var new_time = '';
    if (day <= '00' && hours <= '00' && minutes <= '00' && seconds <= '00') {
      new_time = 0;
    } else {
      new_time = day + " 天 " + hours + " 时 " + minutes + " 分 " + seconds + " 秒";//排列时间
    }

    // console.log(new_time);
    var group_content = that.data.group_content;//获取产品
    group_content[index].time = new_time;
    var time_all = that.data.time_all;//获取时间戳
    time_all[index] = Times;

    that.setData({
      group_content: group_content,
      time_all: time_all,
    })
  },
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function () {
  },

	/**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function () {
    var that = this;
    timer = setInterval(function () {
      var group_content = that.data.group_content;
      var time_all = that.data.time_all;
      for (var i = 0; i < group_content.length; i++) {
        that.time_cipher(time_all[i], i)
      }
    }, 1000);


  },
  onHide: function () {
    clearInterval(timer);
  },
  onUnload: function () {
    clearInterval(timer);
  },
	/**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function () {

  },

	/**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function () {

  },

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
  onPullDownRefresh: function () {
    console.log(5555)
  },

	/**
	 * 页面上拉触底事件的处理函数
	 */
  // onReachBottom
  scrolltolower: function () {
    var that = this;
    console.log(that.data);
    console.log(that.data.select_index_num);
    console.log(that.data.defaultpages);
    if (that.data.go_look) {
      console.log("上拉加载更多....")
      that.setData({ go_look: false })
      //数据加载
      //console.log(that.data.defaultpages);
      var page = that.data.defaultpages;
      console.log('***********************************************');
      wx.request({
        //url: app.url + 'api_group/lotteryGroup',
        url: app.url + 'api_team/timeBanner',
        data: {
          page: page,
          day: that.data.select_index_num,
          type: 2
        },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key')
        },
        success: function (res) {
          console.log(res.data.result.list);
          if (res.data.result.list.length > 0) {
            console.log('下拉成功');
            var group_content = that.data.group_content;
            for (var i = 0; i < res.data.result.list.length; i++) {
              group_content.push(res.data.result.list[i]);

              //获得后台转过来的毫秒数 储存在time_box中
              that.data.time_all.push(res.data.result.list[i].timeout)
              // 获得毫秒数  转化  成小时、分钟、秒
              that.time_cipher(res.data.result.list[i].timeout, i);
            }
            //var defaultpages = that.data.defaultpages;
            //++defaultpages;
            that.setData({
              group_content: group_content,
            });
            that.setData({
              defaultpages: ++that.data.defaultpages,
              go_look: true,
            });
          } else {
            //提示信息
            wx.showToast({
              title: '没有更多了',  //标题  
              icon: 'loading',  //图标，支持"success"、"loading"  
              duration: 1200,
            })
            console.log("已经拉到底部了-------------------------------------------");
          }

        }, complete: function () {
          //显示出加载中的提示
          // 	setTimeout(function(){
          // 		if (that.data.go_look==false){
          // 			console.log(5555);
          // 			that.setData({ loadHidden: true, go_look: true })
          // 		}
          // }, 1000)
          that.setData({ loadHidden: true, go_look: true })
          //  wx.showToast({
          //   title: '加载完成',  //标题  
          //   icon: 'success',  //图标，支持"success"、"loading" 
          //   duration: 1200,
          //  }) 
        }

      })
    }
  },

	/**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function () {

  }
})


//转换时间格式结构
function CurentTime(now) {
  var year = now.getFullYear();       //年
  var month = now.getMonth() + 1;     //月
  var day = now.getDate();            //日

  var clock = year + "";
  if (month < 10)
    clock += "0";
  clock += month + "";
  if (day < 10)
    clock += "0";
  clock += day + "";

  return (clock);
}